package com.itheima.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Sku;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class RabbitMQListener {
    @Autowired
    private RestHighLevelClient client;


        @RabbitListener(queues = "GoodsQueue")
        public void Listener(Map message) throws IOException {
            String type = (String)message.get("type");
            if ("save".equals(type)||"update".equals(type)){
                Sku sku = (Sku)message.get("data");
                IndexRequest request =new IndexRequest("sku");
                request.id(sku.getId().toString());
                String jsonUser = JSON.toJSONString(sku);
                request.source(jsonUser, XContentType.JSON);

                IndexResponse response = client.index(request, RequestOptions.DEFAULT);

            }
            if ("delete".equals(type)){
                System.out.println("11111");
                String id = (String)message.get("data");
                DeleteRequest request = new DeleteRequest("sku");
                request.id(id);
                client.delete(request,RequestOptions.DEFAULT);
            }


        }

    }

